

#include "IntStylexManager.hpp"
#include "OperationsManager.hpp"

#include <QMetaMethod>

namespace NSApplication {

	IntStylexManager::IntStylexManager() :
        AbstractManager()
	{

	};


	IntStylexManager::~IntStylexManager() {
		

	}

    void IntStylexManager::addIntStyle(AbstractObject* ins, int index) {
        QString name = ins->className();
        if (!ins || m_objects.contains(name)) return;
        registerObject(ins); 
        QObject* op_object = dynamic_cast<QObject*>(myManager(OperationsManager)->getObjects().value(ins->className()));
        QObject* intstyle_object = dynamic_cast<QObject*>(ins);
        if (!op_object || !intstyle_object) return;
        const QMetaObject* op_meta = op_object->metaObject();
        QHash<QString, QMetaMethod> slot_hash;
        auto makeMethodKey = [](const QMetaMethod& method) {
            return QString("%1(%2)").arg(method.name().constData()).arg(method.parameterTypes().join(",").constData());
        };

        for (int j = 0; j < op_meta->methodCount(); ++j) {
            QMetaMethod slot = op_meta->method(j);
            const auto type = slot.methodType();
            if (type != QMetaMethod::Slot && type != QMetaMethod::Method) continue;
            slot_hash.insert(makeMethodKey(slot), slot);
        }
        const QMetaObject* intstyle_meta = intstyle_object->metaObject();
        for (int i = 0; i < intstyle_meta->methodCount(); ++i) {
            QMetaMethod signal = intstyle_meta->method(i);
            if (signal.methodType() != QMetaMethod::Signal) continue;
            const QString slot_name = QString("%1Slot").arg(signal.name().constData());
            const QString slot_key = QString("%1(%2)")
                .arg(slot_name)
                .arg(signal.parameterTypes().join(",").constData());
            if (slot_hash.contains(slot_key)) {
                bool connected = QObject::connect(
                    intstyle_object, signal,
                    op_object, slot_hash[slot_key],
                    Qt::AutoConnection
                );
                qInfo() << "IntStyle Signal:" << signal.name()
                    << "->" << slot_name << (connected ? "connected" : "failed");
            }
        }
        

    }
}
